<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/7/3
 * Time: 15:46
 */

namespace app\modules\controllers;

use Yii;
use app\models\Category;
use app\models\Product;
use crazyfd\qiniu\Qiniu;
use yii\data\Pagination;

class ProductController extends CommonController
{
        public function actionList()
        {
            $model = Product::find();
            $count = $model->count();
            $pager = new Pagination(['totalCount' => $count,'pageSize' => \Yii::$app->params['pageSize']['product']]);
            $products = $model->offset($pager->offset)->limit($pager->limit)->all();
            $this->layout = "layout1";
            return $this->render("products", ['pager' => $pager, 'products' => $products]);
        }

        public function actionAdd()
        {
            $this->layout = "layout1";
            $model = new Product();
            $cate = new Category();
            $list = $cate->getOptions();
            //去除顶级分类
            unset($list[0]);
            if (\Yii::$app->request->isPost) {
                $data = \Yii::$app->request->post();
                $pics = $this->upload();
                if (!$pics) {
                    $model->addError('cover',"封面不能为空");
                } else {
                    $data['Product']['cover'] = $pics['cover'];
                    $data['Product']['pics'] = $pics['pics'];
                }
                if ($pics && $model->add($data)) {
                    Yii::$app->session->setFlash('info', '添加成功');
                } else {
                    Yii::$app->session->setFlash('info', '添加失败');
                }
            }
            return $this->render('add',['opts' => $list,'model' => $model]);
        }

        public function upload()
        {
            if ($_FILES['Product']['error']['cover']>0) {
                return false;
            }
            $qiniu = new Qiniu(Product::AK,Product::SK,Product::DOMAIN,Product::BUCKET);
            $key = uniqid();
            $qiniu->uploadFile($_FILES['Product']['tmp_name']['cover'],$key);
            $cover = $qiniu->getLink($key);
            $pics = [];
            foreach ($_FILES['Product']['tmp_name']['pics'] as $k => $file) {
                if ($_FILES['Product']['tmp_name']['pics'][$k] > 0) {
                    continue;
                }
                $key = uniqid();
                $qiniu->uploadFile($file,$key);
                $pics[$key] = $qiniu->getLink($key);
            }
            return ['cover' => $cover, 'pics' => json_encode($pics)];
        }

        /**
         * 针对七牛图片上传的思路是：先将当前新的图片传上去，然后替换掉变量，再把七牛上旧的链接删掉==》单图
         * 多图：同样先上传，但是只是更改数据库的链接
         * @throws \Exception
         */
        public function actionMod()
        {
            $this->layout = "layout1";
            $model = new Product();
            $cate = new Category();
            $list = $cate->getOptions();
            //去除顶级分类
            unset($list[0]);
            $productid = \Yii::$app->request->get("productid");
            $model = Product::find()->where(['productid' => $productid])->one();
            if (\Yii::$app->request->isPost) {
                $data = \Yii::$app->request->post();
                //读取原来的图片地址
                $data['Product']['cover'] = $model->cover;
                $qiniu = new Qiniu(Product::AK,Product::SK,Product::DOMAIN,Product::BUCKET);
                if ($_FILES['Product']['error']['cover'] == 0) {
                    $key = uniqid();
                    //$_FILES['Product']['tmp_name']['cover']:服务器存储的临时文件名
                    $qiniu->uploadFile($_FILES['Product']['tmp_name']['cover'],$key);
                    $data['Product']['cover'] = $qiniu->getLink($key);
                    //把七牛上旧的图片路径删除
                    $qiniu->delete(basename($model->cover));
                }
                $pics = [];
                foreach ($_FILES['Product']['tmp_name']['pics'] as $k => $file) {
                    if ($_FILES['Product']['error']['pics'][$k] > 0 ){
                        continue;
                    }
                    $key = uniqid();
                    $qiniu->uploadFile($file,$key);
                    $pics[$key] = $qiniu->getLink($key);
                }
                $data['Product']['pics'] = json_encode(array_merge((array)json_decode($model->pics, true), $pics));
                if ($model->load($data) && $model->save()) {
                    \Yii::$app->session->setFlash("info","修改成功");
                } else {
                    \Yii::$app->session->setFlash("info","修改失败");
                }
            }
            return $this->render('add', ['model' => $model, 'opts' => $list]);
        }

        public function actionRemovepic()
        {
            $key = \Yii::$app->request->get("key");
            $productid = \Yii::$app->request->get("productid");
            $model = Product::find()->where(['productid' => $productid])->one();
            $qiniu = new Qiniu(Product::AK,Product::SK,Product::DOMAIN,Product::BUCKET);
            $qiniu->delete($key);
            $pics = json_decode($model->pics,true);
            unset($pics[$key]);
            Product::updateAll(['pics' => json_encode($pics)],['productid' => $productid]);
            return $this->redirect(['product/mod', 'productid' => $productid]);
        }

        public function actionDel()
        {
            $productid = \Yii::$app->request->get("productid");
            $model = Product::find()->where(['productid' => $productid])->one();
            if (empty($model)) {
                return $model->addError("数据不存在");
            }
            $qiniu = new Qiniu(Product::AK,Product::SK,Product::DOMAIN,Product::BUCKET);
            $key = basename($model->cover);
            $qiniu->delete($key);
            $pics = json_decode($model->pics,true);
            foreach($pics as $key=>$file) {
                $qiniu->delete($key);
            }
            Product::deleteAll('productid = :pid', [':pid' => $productid]);
            return $this->redirect(['product/list']);
        }

        public function actionOn()
        {
            $productid = Yii::$app->request->get("productid");
            Product::updateAll(['ison' => '1'], 'productid = :pid', [':pid' => $productid]);
            return $this->redirect(['product/list']);
        }

        public function actionOff()
        {
            $productid = Yii::$app->request->get("productid");
            Product::updateAll(['ison' => '0'], 'productid = :pid', [':pid' => $productid]);
            return $this->redirect(['product/list']);
        }

}